package com.yx.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

public class ShiroRun {
    public static void main(String[] args) {
        //1、初始化获取SecurityManager
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //2、获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        //3、创建token对象，web用用户名密码从页面传递
        AuthenticationToken token = new UsernamePasswordToken("admin","123456");
        //4、完成登录
        try {
            subject.login(token);
            System.out.println("登陆成功");
            //5、判断角色
            boolean role1 = subject.hasRole("role1");
            System.out.println("\n是否拥有该角色?");
            if (role1){
                System.out.println("拥有该角色");
            }else {
                System.out.println("暂不拥有该角色");
            }
            //6、判断权限
            boolean[] permitted = subject.isPermitted("user:insert","user:delete");
            System.out.println("\n是否有用此权限?");
            for (int i = 0; i < permitted.length; i++) {
                if (permitted[i]){
                    System.out.println("拥有此权限");
                }else {
                    System.out.println("暂无权限");
                }
            }
            // checkPermission 方法没有返回值,没权限就会报错
//            subject.checkPermission("user:insert1");
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户名不存在");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码不正确");
        }catch (AuthenticationException e){
            //输出不了
            System.out.println("没权限");
            e.printStackTrace();
        }

    }
}
